import router from '@/router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import { getToken } from '@/utils/auth'
import { usePermissionStore } from './store/modules/permission'

NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login', '/'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // 判断是否登录
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const permissionStore = usePermissionStore()
      // 判断是否有动态路由
      const hasRoutes = permissionStore.asyncRoutes && permissionStore.asyncRoutes.length > 0

      if (hasRoutes) {
        next()
      } else {
        try {
          await permissionStore.generateAsyncRoutes()
          next({ ...to, replace: true })
        } catch (error) {
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 滚动到顶部
  window.scrollTo(0, 0)
  // finish progress bar
  NProgress.done()
})
